<?php

namespace app\common\model;

use think\Db;
use think\Model;

class PanelModel extends Model
{
    //
    public
        $table = 'cms_blog_panel',
        $pk = 'id';

    public function getList()
    {
        $data = Db::query("SELECT id,page_title FROM $this->table");
        foreach ($data as $v) {
            $dataInfo[] = [
                'id' => $v['id'],
                'page_title' => $v['page_title'],
            ];
        }
        return ["code" => 0, "msg" => "", "count" => 1000, "data" => $dataInfo];
    }

    public function getDataInfo()
    {
        $data = Db::query("SELECT id,page_title,rows FROM $this->table");
        foreach ($data as $v) {
            $dataInfo[] = [
                'pageTitle' => $v['page_title'],
                'rows'=>json_decode($v['rows'])
            ];
        }
        return $dataInfo;
    }

    public function updateData($param)
    {
        if (empty($param['pageTitle'])) {
            return ['status' => 0, 'message' => 'pageTitle不能为空'];
        }
        if (empty($param['rows'])) {
            return ['status' => 0, 'message' => 'rows不能为空'];
        }
        $rows = [];
        foreach ($param['rows']['title'] as $key => $val){
            $row['title'] = $val;
            $row['icon'] = $param['rows']['icon'][$key];
            $row['type'] = $param['rows']['type'][$key];
            $row['showBorder'] = $param['rows']['showBorder'][$key];
            $row['url'] = $param['rows']['url'][$key];
            $row['setting'] = !empty($param['rows']['setting'][$key]) ? $param['rows']['setting'][$key] : [];
            $rows[] = $row;
        }
        $update = [
            'page_title' => $param['pageTitle'],
            'rows' => json_encode($rows)
        ];
        if (!empty($param['id'])) {
            $update['update_time'] = time();
            $sql = $this->save($update, ['id' => $param['id']]);
            if (empty($sql)) {
                return ['status' => 0, 'message' => '更新失败'];
            }
            return ['status' => 1, 'message' => '更新成功'];
        } else {
            $update['creation_time'] = time();
            $sql = $this->insert($update);
            if (empty($sql)) {
                return ['status' => 0, 'message' => '添加失败'];
            }
            return ['status' => 1, 'message' => '添加成功'];
        }
    }


}
